package main

func commonChars(words []string) []string {
	result := make([]string, 0)
	if len(words) < 2 {
		if len(words) <= 0 {
			return nil
		}

		for i := 0; i < len(words[0]); i++ {
			result = append(result, string(words[0][i]))
		}
		return result
	}

	arrMap := make([]map[byte]byte, 0)
	minLenMapIndex := 0
	for i := 0; i < len(words); i++ {
		m := map[byte]byte{}

		for j := 0; j < len(words[i]); j++ {
			m[words[i][j]]++
		}

		arrMap = append(arrMap, m)

		if len(arrMap[minLenMapIndex]) > len(m) {
			minLenMapIndex = i
		}
	}

	contrast := arrMap[minLenMapIndex]

	for c, count := range contrast {
		minCharCount := count
		j := 0
		for ; j < len(arrMap); j++ {
			if j == minLenMapIndex {
				continue
			}
			num, ok := arrMap[j][c]
			if !ok {
				break
			}

			if num < minCharCount {
				minCharCount = num
			}
		}

		if j == len(arrMap) {

			for i := 0; i < int(minCharCount); i++ {
				result = append(result, string(c))
			}

		}
	}

	return result
}
